package com.xinxin.intelligenceexam.presenter;

import android.support.annotation.NonNull;

import com.orhanobut.logger.Logger;
import com.xinxin.intelligenceexam.api.Generator;
import com.xinxin.intelligenceexam.api.JavaExamApi;
import com.xinxin.intelligenceexam.base.BaseView;
import com.xinxin.intelligenceexam.contract.RegisterContract;
import com.xinxin.intelligenceexam.domain.HttpResult;
import com.xinxin.intelligenceexam.domain.Student;
import com.xinxin.intelligenceexam.model.RegisterModelImpl;
import com.xinxin.intelligenceexam.utils.GsonUtils;
import com.xinxin.intelligenceexam.utils.ToastUtils;

import java.util.Date;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by x9259 on 2016/11/06
 */

public class RegisterPresenterImpl implements RegisterContract.Presenter {
    RegisterContract.View mView;
    RegisterContract.Model mModel;

    public RegisterPresenterImpl() {
        mModel = new RegisterModelImpl();
    }


    @Override
    public void attachView(BaseView view) {
        mView = (RegisterContract.View) view;
    }

    @Override
    public void register(@NonNull String name, @NonNull String password, @NonNull String studentCode, @NonNull Date birth, @NonNull String className) {
        Student student = new Student();
        student.setName(name);
        student.setPassword(password);
        student.setCode(studentCode);
        student.setBirth(birth);
        student.setClassName(className);
        String studentJson = GsonUtils.toJsonString(student);
        Logger.d(studentJson);
        //RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), studentJson);
        Generator.createService(JavaExamApi.class).studentRegister(studentJson).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.snackBarShow("网络或其他异常");
                    }

                    @Override
                    public void onNext(HttpResult httpResult) {
                        if (httpResult.getStatus() == 0) {
                            mView.snackBarShow("服务器处理异常");
                        }else {
                            ToastUtils.showShort("注册成功");
//                        mView.gotomain();
                            mView.getoLogin();
                        }
                    }
                });

    }
}